package com.schoolgard.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.schoolegard.services.UsersService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.entitybean.Role;
import com.schoolgard.entitybean.RoleOfUsers;
import com.schoolgard.entitybean.RolePrivilege;
import com.schoolgard.entitybean.Users;
import com.supersystem.utils.Md5Utils;
import com.supersystem.utils.StringUtil;
import com.supersystem.utils.TypeUtils;

public class LoginAction extends BaseAction{
    
	private static Logger logger = Logger.getLogger(LoginAction.class);
	private static final long serialVersionUID = 201111302313L;
	
	private UsersService usersService;
	public void setUsersService(UsersService usersService) {
		this.usersService = usersService;
	}

	public String login()
	{
		String userLoginId = request.getParameter("userLoginId");
		String password = request.getParameter("password");
		
		try {
			Users user = usersService.findByLoginId(userLoginId); //查找id为loginId的用户
			if(user == null){
				writeToResponse("{\"success\": false,\"msg\":\"登录失败，不存在此用户\"}");
				return null;
			}else if(!user.getStatus()){ //用户禁用了
				writeToResponse("{\"success\": false,\"msg\":\"登录失败，此用户已经停用\"}");
				return null;
			}else{
				if(Md5Utils.getMD5String(password).equals(user.getPassword())){
					setAuthority(user); //设置权限，菜单权限
					writeToResponse("{\"success\": true,\"msg\":\"登录成功，正在跳转...\"}");
				}else{
					writeToResponse("{\"success\": false,\"msg\":\"密码错误，请重新输入\"}");
					return null;
				}
			}
		} catch (Exception e) {
			writeToResponse("{\"success\": false,\"msg\":\"登录失败\"}");
			logger.error("登录服务器错误", e);
			e.printStackTrace();
		}
		return null;
	}
	
	public void logout()
	{
		HttpSession session = request.getSession();
		session.invalidate();
		writeToResponse("1");
	}
	
	/**
	 * 查询出菜单权限，将它放到session里面
	 * @param user 员工登录信息
	 */
	public void setAuthority(Users user)
	{   
		if(user != null){
			setUserAuthority(user);
		}
	}
	/**
	 * 设置员工权限，菜单权限
	 * 根据员工id查找角色用户表，查找到角色
	 * 再根据所有角色id查找拥有的菜单(角色菜单表，既权限表)，需要去重
	 * 再将菜单id保存到session中
	 * @param user
	 */
	public void setUserAuthority(Users user)
	{
		if(user == null) return;
		StringBuffer catalogs = new StringBuffer(); //菜单权限数据
		List<Role> roles = this.getRoles(user.getRoleOfUserses()); //获取角色
		for (Role role : roles) {
			Set<RolePrivilege> privileges = role!=null?role.getRolePrivileges():null;
			if(privileges != null && !privileges.isEmpty()){
				Iterator<RolePrivilege> ite = privileges.iterator();
				while(ite.hasNext()){
					catalogs.append(ite.next().getPrivilegeMenu()); //注意 ：默认保存的菜单格式为001,001001,最后面有一个逗号。
				}
			}
			
		}
		//设置当前用户的菜单权限
		getSession().put(TypeUtils.USER_CATALOG_IDS, StringUtil.delRepeatString(catalogs.toString()));
		getSession().put(TypeUtils.USER, user);
	}
	
	/**
	 * 根据角色用户表，获取用户的所有角色
	 * 一个用户可以对应多个角色
	 * @param roleTouser
	 * @return
	 */
	private List<Role> getRoles(Set<RoleOfUsers> roleTouser)
	{
		if(roleTouser.isEmpty()) {
			return new ArrayList<Role>();
		}
		Iterator<RoleOfUsers> ite = roleTouser.iterator();
		List<Role> roles = new ArrayList<Role>();
		StringBuffer rolebf = new StringBuffer();
		while(ite.hasNext()){
			rolebf.append(ite.next().getRole()).append(",");
		}
		String[] roleArray = StringUtil.delRepeatString(rolebf.toString()).split(",");
		for(int i = 0 ; i<roleArray.length ; i++){
			roles.add(usersService.findRoleById(Long.valueOf(roleArray[i].trim())));
		}
		return roles;
	}
}
